package com.huatech.service.impl;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.huatech.dao.SystemConfigDao;
import com.huatech.domain.SystemConfig;
import com.huatech.service.SystemConfigService;

@Service("systemConfigService")
public class SystemConfigServiceImpl implements SystemConfigService {

	private ConcurrentHashMap<String, SystemConfig> systemConfigCache = new ConcurrentHashMap<>();
	private static final String SYSTEM_CONFIG_CACHE_KEY = "sc_%s";

	@Resource
	private SystemConfigDao systemConfigDao;

	@Override
	public int save(SystemConfig entity) {
		return systemConfigDao.save(entity);
	}

	@Override
	public SystemConfig find(long id) {
		return systemConfigDao.find(id);
	}

	@Override
	public int updateSelective(SystemConfig entity) {
		SystemConfig config = find(entity.getId());
		String cacheKey = String.format(SYSTEM_CONFIG_CACHE_KEY, config.getConfigCode());
		systemConfigCache.remove(cacheKey);
		return systemConfigDao.updateSelective(entity);
	}

	@Override
	public List<SystemConfig> findList(Map<String, Object> map) {
		return systemConfigDao.findList(map);
	}

	@Override
	public SystemConfig findByConfigCode(String configCode) {
		String cacheKey = String.format(SYSTEM_CONFIG_CACHE_KEY, configCode);
		if (systemConfigCache.containsKey(cacheKey)) {
			return systemConfigCache.get(cacheKey);
		}
		SystemConfig config = systemConfigDao.findByConfigCode(configCode);
		if (config != null) {
			systemConfigCache.put(cacheKey, config);
		}
		return config;
	}

	@Override
	public String getConfigValue(String configCode) {
		SystemConfig config = findByConfigCode(configCode);
		return config == null ? null : config.getConfigValue();
	}

	@Override
	public int getCount(Map<String, Object> map) {
		return systemConfigDao.getCount(map);
	}
	
	
}
